package cn.lxtkj.springboot.service;

import cn.lxtkj.springboot.controller.admin.AttachController;
import cn.lxtkj.springboot.entity.*;
import cn.lxtkj.springboot.mapper.CommentMapper;
import cn.lxtkj.springboot.mapper.ArticleMapper;
import cn.lxtkj.springboot.mapper.AttachMapper;
import cn.lxtkj.springboot.mapper.MetasMapper;
import cn.lxtkj.springboot.utils.DateKit;
import cn.lxtkj.springboot.utils.TaleUtils;
import cn.lxtkj.springboot.utils.ZipUtils;
import cn.lxtkj.springboot.utils.backup.Backup;
import com.github.pagehelper.PageHelper;
import cn.lxtkj.springboot.dto.Types;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import cn.lxtkj.springboot.model.Bo.BackResponseBo;
import cn.lxtkj.springboot.model.Bo.StatisticsBo;
import cn.lxtkj.springboot.exception.TipException;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

@Service
public class SiteService {
    private static Logger log = Logger.getLogger(SiteService.class);

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private AttachMapper attachMapper;

    @Resource
    private MetasMapper metasMapper;

    
    public List<Comment> recentComments(int limit) {
        log.debug("Enter recentComments method:limit={}"+limit);
        if (limit < 0 || limit > 10) {
            limit = 10;
        }
        PageHelper.startPage(1, limit);
        List<Comment> byPage = commentMapper.getList();
        log.debug("Exit recentComments method");
        return byPage;
    }

    public List<Article> recentContents(int limit) {
        log.debug("Enter recentContents method");
        if (limit < 0 || limit > 10) {
            limit = 10;
        }
//        PageHelper.startPage(1, limit);
        List<Article> list = articleMapper.getRecentList(limit);
        log.debug("Exit recentContents method");
        return list;
    }

    public BackResponseBo backup(String bk_type, String bk_path, String fmt) throws Exception {
        BackResponseBo backResponse = new BackResponseBo();
        if (bk_type.equals("attach")) {
            if (StringUtils.isBlank(bk_path)) {
                throw new TipException("请输入备份文件存储路径");
            }
            if (!(new File(bk_path)).isDirectory()) {
                throw new TipException("请输入一个存在的目录");
            }
            String bkAttachDir = AttachController.CLASSPATH + "upload";
            String bkThemesDir = AttachController.CLASSPATH + "templates/themes";

            String fname = DateKit.dateFormat(new Date(), fmt) + "_" + TaleUtils.getRandomNumber(5) + ".zip";

            String attachPath = bk_path + "/" + "attachs_" + fname;
            String themesPath = bk_path + "/" + "themes_" + fname;

            ZipUtils.zipFolder(bkAttachDir, attachPath);
            ZipUtils.zipFolder(bkThemesDir, themesPath);

            backResponse.setAttachPath(attachPath);
            backResponse.setThemePath(themesPath);
        }
        if (bk_type.equals("db")) {

            String bkAttachDir = AttachController.CLASSPATH + "upload/";
            if (!(new File(bkAttachDir)).isDirectory()) {
                File file = new File(bkAttachDir);
                if (!file.exists()) {
                    file.mkdirs();
                }
            }
            String sqlFileName = "tale_" + DateKit.dateFormat(new Date(), fmt) + "_" + TaleUtils.getRandomNumber(5) + ".sql";
            String zipFile = sqlFileName.replace(".sql", ".zip");

            Backup backup = new Backup(TaleUtils.getNewDataSource().getConnection());
            String sqlContent = backup.execute();

            File sqlFile = new File(bkAttachDir + sqlFileName);
            write(sqlContent, sqlFile, Charset.forName("UTF-8"));

            String zip = bkAttachDir + zipFile;
            ZipUtils.zipFile(sqlFile.getPath(), zip);

            if (!sqlFile.exists()) {
                throw new TipException("数据库备份失败");
            }
            sqlFile.delete();

            backResponse.setSqlPath(zipFile);

            // 10秒后删除备份文件
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    new File(zip).delete();
                }
            }, 10 * 1000);
        }
        return backResponse;
    }

//    @Override
//    public CommentVo getComment(Integer coid) {
//        if (null != coid) {
//            return articleMapper.selectByPrimaryKey(coid);
//        }
//        return null;
//    }
//

    public StatisticsBo getStatistics() {
        log.debug("Enter getStatistics method");
        StatisticsBo statistics = new StatisticsBo();

        Article article = new Article();
        ContentVo contentVo = new ContentVo();

        contentVo.createCriteria().andTypeEqualTo(Types.ARTICLE.getType()).andStatusEqualTo(Types.PUBLISH.getType());
        Long articles =   articleMapper.countByExample(contentVo);

        Long comments = commentMapper.countByExample(new CommentVo());

        Long attachs = attachMapper.countByExample(new AttachVo());

        MetasVo metasVo = new MetasVo();
        metasVo.createCriteria().andTypeEqualTo(Types.LINK.getType());
        Long links = metasMapper.countByExample(metasVo);

        statistics.setArticles(articles);
        statistics.setComments(comments);
        statistics.setAttachs(attachs);
        statistics.setLinks(links);
        log.debug("Exit getStatistics method");
        return statistics;
    }
//
//    @Override
//    public List<ArchiveBo> getArchives() {
//        LOGGER.debug("Enter getArchives method");
//        List<ArchiveBo> archives = contentDao.findReturnArchiveBo();
//        if (null != archives) {
//            archives.forEach(archive -> {
//                ContentVoExample example = new ContentVoExample();
//                ContentVoExample.Criteria criteria = example.createCriteria().andTypeEqualTo(Types.ARTICLE.getType()).andStatusEqualTo(Types.PUBLISH.getType());
//                example.setOrderByClause("created desc");
//                String date = archive.getDate();
//                Date sd = DateKit.dateFormat(date, "yyyy年MM月");
//                int start = DateKit.getUnixTimeByDate(sd);
//                int end = DateKit.getUnixTimeByDate(DateKit.dateAdd(DateKit.INTERVAL_MONTH, sd, 1)) - 1;
//                criteria.andCreatedGreaterThan(start);
//                criteria.andCreatedLessThan(end);
//                List<ContentVo> contentss = contentDao.selectByExample(example);
//                archive.setArticles(contentss);
//            });
//        }
//        LOGGER.debug("Exit getArchives method");
//        return archives;
//    }
//
//    @Override
//    public List<MetaDto> metas(String type, String orderBy, int limit){
//        LOGGER.debug("Enter metas method:type={},order={},limit={}", type, orderBy, limit);
//        List<MetaDto> retList=null;
//        if (StringUtils.isNotBlank(type)) {
//            if(StringUtils.isBlank(orderBy)){
//                orderBy = "count desc, a.mid desc";
//            }
//            if(limit < 1 || limit > WebConst.MAX_POSTS){
//                limit = 10;
//            }
//            Map<String, Object> paraMap = new HashMap<>();
//            paraMap.put("type", type);
//            paraMap.put("order", orderBy);
//            paraMap.put("limit", limit);
//            retList= metasMapper.selectFromSql(paraMap);
//        }
//        LOGGER.debug("Exit metas method");
//        return retList;
//    }
//

    private void write(String data, File file, Charset charset) {
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            os.write(data.getBytes(charset));
        } catch (IOException var8) {
            throw new IllegalStateException(var8);
        } finally {
            if(null != os) {
                try {
                    os.close();
                } catch (IOException var2) {
                    var2.printStackTrace();
                }
            }
        }

    }
}
